import { getCartList, changeCount, del } from '@/api/cart'
import { Toast } from 'vant'
export default {
  namespaced: true,
  state () {
    return {
      cartList: []
    }
  },
  mutations: {
    setCartList (state, newList) {
      state.cartList = newList
    },
    setisChecked (state, goodsId) {
      const goodsList = state.cartList.find(item => item.goods_id === goodsId)
      goodsList.isChecked = !goodsList.isChecked
    },
    changeCount (state, { goodsId, value }) {
      const goodslist = state.cartList.find(item => item.goods_id === goodsId)
      goodslist.goods_num = value
    },
    toggleAllCheck (state, flag) {
      state.cartList.forEach(item => { item.isChecked = flag })
    }
  },
  getters: {
    cartTotal (state) {
      return state.cartList.reduce((sum, item) => sum + item.goods_num, 0)
    },
    selCartList (state) {
      return state.cartList.filter(item => item.isChecked)
    },
    selCount (state, getters) {
      return getters.selCartList.reduce((sum, item) => item.goods_num + sum, 0)
    },
    selprice (state, getters) {
      return getters.selCartList.reduce((sum, item) => item.goods.goods_price_min * item.goods_num + sum, 0).toFixed(2)
    },
    getisChecked (state) {
      return state.cartList.every(item => item.isChecked)
    }
  },
  actions: {
    async getCartActin (context) {
      const { data } = await getCartList()
      console.log(data)
      data.list.forEach(item => {
        item.isChecked = true
      })
      context.commit('setCartList', data.list)
    },
    async changeCountAction (context, obj) {
      const { value, goodsId, skuid } = obj
      context.commit('changeCount', { goodsId, value })
      await changeCount(goodsId, value, skuid)
    },
    async delAction (context) {
      const getisChecked = context.getters.selCartList
      const cartId = getisChecked.map(item => item.id)
      await del(cartId)
      Toast('删除成功')
      context.dispatch('getCartActin')
    }
  }
}
